<?php

namespace app\admin\controller;

use app\model\AdminModel;
use app\model\AdminOptionModel;
use Shopwwi\LaravelCache\Cache;
use support\Request;
use Tinywan\Captcha\Captcha;
use zjkal\TimeHelper;

class PublicController
{
    
    /**
     * 管理员登录
     */
    public function login(Request $request){

        $all = $request->all();

        if(empty($all['username']) || empty($all['password'])){
            return error("请输入用户名与密码");
        }

        if(empty($all['code'])){
            return error("请输入图形验证码");
        }

        if (false === Captcha::check($all['code'],$all['key'])) {
            // 验证失败
            return error("图形验证码错误");
        };

        $detail = AdminModel::where("username",$all['username'])->find();

        if(empty($detail) || $detail['password'] != get_password($all['password'])){
            return error("用户不存在或密码错误",[],[]);
        }

        //生成token
        $token = md5(uniqid($detail['id']));

        Cache::tags('admin')->put('token_'.$token,$detail['id'],TimeHelper::secondDay(365));

        return success("登录成功",['token'=>$token]);
    }

    /**
     * 获取网站标题
     */
    public function getTitle(Request $request){
        $option = AdminOptionModel::where("option_name",'setting')->find();
        if(empty($option) || empty($option['option_value'])){
            $title = '后台管理';
        }else{
            $title = json_decode($option['option_value'],true)['title'] ?? '后台管理';
        }
        return success("ok",['title'=>$title]);
    }

    /**
     * 获取图形验证码
     */
    public function getCaptcha(){

        $captcha = Captcha::base64();

        return success("ok",$captcha);
    }

}
